package com.nytd.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RequestMapping("/m1")
@RestController
public class demo01 {

    @RequestMapping("/r1")
    public String method01(@RequestBody Person person) {
        return person.toString();
    }

    @RequestMapping("/r2/{id}/{name}")
    public String method02(@PathVariable int id, @PathVariable("name") String userName) {
        return "id: " + id + ", userName: " + userName;
    }

    @RequestMapping("/r3")
    public String getFile(@RequestPart(value = "file", required = false) MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        file.transferTo(new File("d:/安装包下载/"
                + name));
        return "接收到文件: " + name;
    }

    @RequestMapping("/r4")
    public String method03(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        StringBuilder s = new StringBuilder();
        if (cookies != null) {
            for (Cookie c : cookies) {
                s.append(c.getName() + ": " + c.getValue() + " ");
            }
        }
        return "cookies: " + s;
    }

    @RequestMapping("/r5")
    public String method04(@CookieValue("name") String useName) {
        return "useName: " + useName;
    }

    @RequestMapping("/r6")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute("userName", "zhangsan");
        }
        return "session 存储成功";
    }

    @RequestMapping("/r7")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        String userName = null;
        if (session != null && session.getAttribute("userName") != null) {
            userName = (String) session.getAttribute("userName");
        }
        return "userName: " + userName;
    }

}
